package BaiDu;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

/**
 * @author zhangmin
 * @create 2022-10-11 19:07
 */
public class Main_1011 {
    public static void main(String[] args) {
        int n=5;
        int[] nums=new int[]{1,2,3,2,2};
        //统计每个数字出现的次数
        Map<Integer,Integer> map=new HashMap<>();
        for (int num:nums) {
            map.put(num,map.getOrDefault(num,0)+1);
        }
        int res=0;
        while (!map.isEmpty()){
            //计算出当前所有元素中，每个数字被删除时会连带删除的数字总和
            /*PriorityQueue<int[]> pq=new PriorityQueue<>((a,b)->{
                return a[1]-b[1];
            });*/
            int minNum=-1,minSum=Integer.MAX_VALUE;
            for (Map.Entry<Integer,Integer> entry:map.entrySet()) {
                int num= entry.getKey();
                int deleteSum=map.getOrDefault(num-1,0)*(num-1)+
                        map.getOrDefault(num+1,0)*(num+1);
                if (deleteSum<minSum){
                    minNum=num;
                    minSum=deleteSum;
                }
            }
            //找到连带删除和最小的一个数字删除
            int top = minNum;
            res+=top;
            map.put(top,map.get(top)-1);
            if (map.get(top)==0) {
                map.remove(top);
            }
            if (map.containsKey(top-1)){
                map.remove(top-1);
            }
            if (map.containsKey(top+1)){
                map.remove(top+1);
            }
        }
        System.out.println(res);
    }
}
